package com.jack.rpc.proxy;

import sun.tools.tree.ShiftRightExpression;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * rpc 客户端代理类
 *
 * @author jie
 * @date 2018/8/9
 */
public class RpcClient {

    public <T> T getProxy(final Class<T> interfaceClass, final InetSocketAddress inetSocketAddress) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket = null;
                Object result = null;
                try {
                    socket = new Socket();
                    //建立与服务提供方的连接
                    socket.connect(inetSocketAddress);
                    try (
                        ObjectOutputStream serializer = new ObjectOutputStream(socket.getOutputStream());
                        ObjectInputStream deSerializer = new ObjectInputStream(socket.getInputStream())
                    ) {
                        //序列化一些列接口名，方法名，参数等给服务端
                        serializer.writeUTF(interfaceClass.getName());
                        serializer.writeUTF(method.getName());
                        serializer.writeObject(method.getParameterTypes());
                        serializer.writeObject(args);

                        result = deSerializer.readObject();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(socket != null){
                        socket.close();
                    }
                }
                return result;
            }
        });
    }
}
